<template>
  <div class="thePage">
    <van-form @submit="onSubmit">
      <van-field v-model="loginForm.name" name="name" label="用户名" placeholder="用户名"
                 :rules="[{ required: true, message: '请填写用户名' }]"/>
      <van-field v-model="loginForm.password" type="password" name="password" label="密码" placeholder="密码"
                 :rules="[{ required: true, message: '请填写密码' }]"/>
      <div style="margin: 16px;">
        <van-button block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>

    <div>
      <van-button @click="onRegister">若还没账号，点击前往注册</van-button>
    </div>
  </div>
</template>

<script>

//1.导入封装后的接口
import {loginAPI} from '@/api/user.js';
import * as Auth from "@/utils/auth.js"
import {setUserLocal} from "../../utils/auth";
import {Dialog} from "vant";
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {name: 'dff', password: '111111'}//表单自动提交
    };
  },
  //在生命周期函数中调用API接口从后端取业务数据
  created() {
    //使用封装的方法，从本地存储中获取用户名
    this.loginForm.name = Auth.getUserLocal().name;
  },

  methods: {
    onSubmit() {
      //console.log('submit', this.loginForm);
      //准备参数
      let params = {
        name: this.loginForm.name,
        password: this.loginForm.password
      };
      //调用接口
      loginAPI(params).then(result => {

        if (result.data===undefined){

          Dialog.confirm({
            title: "要重新登录吗?",
            message: "密码错误",
          })
        }else {
          setUserLocal(result.data)

          //实现路由跳转页面 看看当前路由是否指定有重定向地址 否则跳转 user

          let toPath = this.$route.params.redirect || "user";
          //延时1秒后路由跳转
          setTimeout(() => {
            this.$router.replace({
              path: toPath
            });
          }, 1000);
        }
      });
    },

    onRegister() {
      //路由跳转
      this.$router.push({name: 'register'});
    }
  }
};
</script>

<style lang="less" scoped="scoped">

.thePage {
  margin: 100px 20px;
}

.title-container {
  font-size: 30px;
  text-align: center;
}

.van-cell {
  margin-bottom: 30px;
  font-size: 20px;
}

.van-cell__title {
  font-size: 18px;
}

::v-deep .van-field__label {
  width: 5.2em;
}

.van-button--normal {
  font-size: 20px;
}
</style>
